<template>
  <div class="role-list-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-title">
        <h2>角色管理</h2>
        <p>管理系统中的所有角色信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:add')">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="角色名称">
          <el-input 
            v-model="searchForm.roleName" 
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input 
            v-model="searchForm.roleCode" 
            placeholder="请输入角色编码"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="全部" :value="null"/>
            <el-option label="正常" :value="1"/>
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button 
            type="danger" 
            :disabled="selectedRoles.length === 0" 
            @click="handleBatchDelete"
            v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:delete')"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="loadRoleList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table 
        :data="roleList" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="roleCode" label="角色编码" min-width="120" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:edit')"
            />
            <el-tag v-else :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click="handleEdit(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:edit')"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              link 
              size="small" 
              @click="handleAssignPermissions(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:edit')"
            >
              分配权限
            </el-button>
            <el-button 
              type="danger" 
              link 
              size="small" 
              @click="handleDelete(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
      v-if="userStore.userInfo?.username === 'admin' || hasPermission('system:role:edit')"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleName">
              <el-input 
                v-model="roleForm.roleName" 
                placeholder="请输入角色名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色编码" prop="roleCode">
              <el-input 
                v-model="roleForm.roleCode" 
                placeholder="请输入角色编码"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="roleForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="角色描述" prop="description">
              <el-input 
                v-model="roleForm.description" 
                type="textarea"
                :rows="3"
                placeholder="请输入角色描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
      :before-close="handlePermissionDialogClose"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ children: 'children', label: 'permissionName' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissions"
        :default-expand-all="true"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlePermissionDialogClose">取消</el-button>
          <el-button type="primary" :loading="permissionSubmitLoading" @click="handlePermissionSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getRoleList, createRole, updateRole, deleteRole, 
  batchDeleteRoles, toggleRoleStatus, getPermissionList, assignRolePermissions
} from '@/api/role'
import {
  Plus, Search, Refresh, Delete, Edit
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const roleList = ref([])
const selectedRoles = ref([])

// 搜索表单
const searchForm = reactive({
  roleName: '',
  roleCode: '',
  status: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentRoleId = ref(null)
const submitLoading = ref(false)
const roleFormRef = ref(null)

// 权限分配对话框
const permissionDialogVisible = ref(false)
const permissionSubmitLoading = ref(false)
const permissionTreeRef = ref(null)
const permissionTree = ref([])
const checkedPermissions = ref([])
const currentPermissionRoleId = ref(null)

// 角色表单
const roleForm = reactive({
  roleName: '',
  roleCode: '',
  description: '',
  status: 1
})

// 表单验证规则
const roleFormRules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' },
    { min: 2, max: 50, message: '角色编码长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色')

// 权限检查 - 取消权限认证，所有登录用户都可以访问
const hasPermission = (permission) => {
  return true
}

// 时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getRoleList(params)
    roleList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadRoleList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    roleName: '',
    roleCode: '',
    status: null
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadRoleList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadRoleList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

// 新增角色
const handleAdd = () => {
  isEdit.value = false
  currentRoleId.value = null
  resetRoleForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  isEdit.value = true
  currentRoleId.value = row.id
  Object.assign(roleForm, {
    ...row
  })
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色"${row.roleName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedRoles.value.map(role => role.id)
    await batchDeleteRoles(ids)
    ElMessage.success('批量删除成功')
    loadRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    // 检查是否为管理员账号
    const isAdmin = userStore.userInfo?.username === 'admin'
    
    if (isAdmin) {
      // 管理员直接允许修改
      await toggleRoleStatus(row.id, row.status)
      ElMessage.success(`角色已${row.status === 1 ? '启用' : '禁用'}`)
    } else if (hasPermission('system:role:edit')) {
      // 有权限的用户允许修改
      await toggleRoleStatus(row.id, row.status)
      ElMessage.success(`角色已${row.status === 1 ? '启用' : '禁用'}`)
    } else {
      // 无权限用户不允许修改
      throw new Error('您没有修改角色状态的权限')
    }
  } catch (error) {
    console.error('更新角色状态失败:', error)
    ElMessage.error(error.message || '更新角色状态失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 分配权限
const handleAssignPermissions = async (row) => {
  try {
    currentPermissionRoleId.value = row.id
    
    // 加载权限树
    const response = await getPermissionList()
    permissionTree.value = response.data || []
    
    // 获取角色当前权限
    const roleDetail = await getRoleDetail(row.id)
    checkedPermissions.value = roleDetail.data.permissionIds || []
    
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('加载权限数据失败:', error)
    ElMessage.error('加载权限数据失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    submitLoading.value = true
    
    const formData = { ...roleForm }
    
    // 检查是否为管理员账号
    const isAdmin = userStore.userInfo?.username === 'admin'
    
    if (isEdit.value) {
      if (isAdmin) {
        await updateRole(currentRoleId.value, formData)
        ElMessage.success('更新成功')
      } else if (!hasPermission('system:role:edit')) {
        throw new Error('您没有编辑角色的权限')
      } else {
        await updateRole(currentRoleId.value, formData)
        ElMessage.success('更新成功')
      }
    } else {
      if (isAdmin || hasPermission('system:role:add')) {
        await createRole(formData)
        ElMessage.success('创建成功')
      } else {
        throw new Error('您没有创建角色的权限')
      }
    }
    
    dialogVisible.value = false
    loadRoleList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 权限分配提交
const handlePermissionSubmit = async () => {
  try {
    permissionSubmitLoading.value = true
    
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const permissionIds = [...checkedKeys, ...halfCheckedKeys]
    
    await assignRolePermissions(currentPermissionRoleId.value, permissionIds)
    ElMessage.success('权限分配成功')
    
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('权限分配失败:', error)
    ElMessage.error('权限分配失败')
  } finally {
    permissionSubmitLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = (done) => {
  dialogVisible.value = false
  resetRoleForm()
  if (typeof done === 'function') {
    done()
  }
}

const handlePermissionDialogClose = (done) => {
  permissionDialogVisible.value = false
  checkedPermissions.value = []
  currentPermissionRoleId.value = null
  if (typeof done === 'function') {
    done()
  }
}

// 重置表单
const resetRoleForm = () => {
  Object.assign(roleForm, {
    roleName: '',
    roleCode: '',
    description: '',
    status: 1
  })
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadRoleList()
})
</script>

<style scoped>
.role-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title h2 {
  color: #303133;
  margin: 0 0 8px 0;
  font-size: 24px;
}

.header-title p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: -18px;
}

.search-form .el-select {
  min-width: 120px;
}

.table-card {
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .table-toolbar {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
